package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.HasStockTo;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.UserMemberVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.interceptor.OrderInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.to.SpuInfoTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {


    @Resource
    OrderItemService orderItemService;

    @Resource
    MemberFeignService memberFeignService;

    @Resource
    CartFeignService cartFeignService;

    @Resource
    WareFeignService wareFeignService;

    @Resource
    PaymentInfoService paymentInfoService;
    
    @Resource
    ThreadPoolExecutor executor;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    ProductFeignService productFeignService;

    @Resource
    RabbitTemplate rabbitTemplate;

    private ThreadLocal<OrderSubmitVo> orderConfirmVoThreadLocal = new ThreadLocal<>();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 订单确认页 返回需要用到得数据
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        //1.远程查询所有的收货列表
        ThreadLocal<UserMemberVo> loginUser = OrderInterceptor.loginUser;
        UserMemberVo userMemberVo = loginUser.get();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            orderConfirmVo.setAddress(memberFeignService.get(userMemberVo.getId()));
        }, executor);
        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //2. 远程查询所有选中得购物项
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> orderItemVos = cartFeignService.currentUserItems();
            orderConfirmVo.setItems(orderItemVos);
            //feign 在远程调用之前要构造请求，调用很多的拦截器
        }, executor).thenRunAsync(()->{
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> collect = items.stream().map(item -> {
                return item.getSkuId();
            }).collect(Collectors.toList());
            R skuStock = wareFeignService.getSkuStock(collect);
            List<HasStockTo> datas = skuStock.getData("data", new TypeReference<List<HasStockTo>>() {
            });
//            HashMap<Long, Boolean> stock = new HashMap<>();
//            for (HasStockTo data : datas) {
//                stock.put(data.getSkuId(),data.getHasStock());
//            }

            if(datas!=null&&datas.size()>0){
                Map<Long, Boolean> stock = datas.stream().collect(Collectors.toMap(HasStockTo::getSkuId, HasStockTo::getHasStock));
                orderConfirmVo.setStock(stock);
            }
        });


        //3. 用户积分
        Integer integration = userMemberVo.getIntegration();
        orderConfirmVo.setIntegration(integration);

        //其他数据自动计算

        //todo  防重令牌
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+userMemberVo.getId(),token,30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);

        CompletableFuture.allOf(cartFuture,getAddressFuture).get();
        return orderConfirmVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        orderConfirmVoThreadLocal.set(vo);
        //  创建订单   所库存  验价格  验令牌
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);
        //1.验令牌 
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        ThreadLocal<UserMemberVo> loginUser = OrderInterceptor.loginUser;
        UserMemberVo userMemberVo = loginUser.get();
        String orderToken = vo.getOrderToken();
        // 原子验证令牌和删除令牌
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + userMemberVo.getId()), orderToken);
        if(result==0L){
            responseVo.setCode(1);
            return responseVo;
            //令牌验证失败
        }
        //验证成功
        OrderCreateTo order = createOrder();
        BigDecimal payAmount = order.getOrder().getPayAmount();
        BigDecimal payPrice = vo.getPayPrice();
        BigDecimal decimal = payAmount.subtract(payPrice);
        if(Math.abs(decimal.doubleValue())<0.01){
            //验价成功
            //3.保存订单数据
            saveOrder(order);
            //4.库存锁定
            //订单号，所有订单项（skuId ,skuName ,num）
            WareSkuLockVo lockVo = new WareSkuLockVo();
            lockVo.setOrderSn(order.getOrder().getOrderSn());
            List<OrderItemVo> collect = order.getOrderItems().stream().map(item -> {
                OrderItemVo itemVo = new OrderItemVo();
                itemVo.setSkuId(item.getSkuId());
                itemVo.setTitle(item.getSkuName());
                itemVo.setCount(item.getSkuQuantity());
                return itemVo;
            }).collect(Collectors.toList());
            lockVo.setLocks(collect);
            R r = wareFeignService.orderLock(lockVo);
            if (r.getCode()==0) {
                //锁成功
                responseVo.setOrderEntity(order.getOrder());
                //todo 订单创建成功，发送消息 给mq
                rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                return responseVo;
            }else {
                responseVo.setCode(3);
                return responseVo;
                //锁失败了
            }
        }else {
            //验价失败 返回
            responseVo.setCode(2);
            return responseVo;
        }
    }

    @Override
    public OrderEntity getOrderBySn(String orderSn) {
        LambdaQueryWrapper<OrderEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderEntity::getOrderSn,orderSn);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {
        String orderSn = orderEntity.getOrderSn();
        LambdaQueryWrapper<OrderEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderEntity::getOrderSn,orderSn);
        OrderEntity entity = baseMapper.selectOne(wrapper);
        if(entity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())){
            //待付款状态  需要关单
            OrderEntity newEntity = new OrderEntity();
            newEntity.setId(entity.getId());
            newEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(newEntity);
            //发给mq一个
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(entity,orderTo);
            rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        OrderEntity entity = getOrderBySn(orderSn);
        PayVo payVo = new PayVo();
        payVo.setTotal_amount(entity.getPayAmount().setScale(2,BigDecimal.ROUND_UP).toString());
        payVo.setOut_trade_no(orderSn);
        payVo.setBody("备注");
        payVo.setSubject("标题");
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        UserMemberVo memberVo = OrderInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new LambdaQueryWrapper<OrderEntity>().eq(OrderEntity::getMemberId,memberVo.getId()).orderByDesc(OrderEntity::getId)
        );

        List<OrderEntity> collect = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> list = orderItemService.list(new LambdaQueryWrapper<OrderItemEntity>().eq(OrderItemEntity::getOrderSn, order.getOrderSn()));
            order.setOrderItemEntityList(list);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(collect);
        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo vo) {
        PaymentInfoEntity entity = new PaymentInfoEntity();
        entity.setAlipayTradeNo(vo.getTrade_no());
        entity.setOrderSn(vo.getOut_trade_no());
        entity.setPaymentStatus(vo.getTrade_status());
        entity.setCallbackTime(vo.getNotify_time());

        paymentInfoService.save(entity);
        System.err.println(vo.getTrade_status());
        if("TRADE_SUCCESS".equals(vo.getTrade_status())||"TRADE_FINISHED".equals(vo.getTrade_status())){
            String outTradeNo = vo.getOut_trade_no();
            baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrder) {
        //todo 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrder.getOrderSn());
        orderEntity.setMemberId(seckillOrder.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = seckillOrder.getSeckillPrice().multiply(new BigDecimal("" + seckillOrder.getSeckillPrice().toString()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);

        // todo 保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(seckillOrder.getOrderSn());
        itemEntity.setRealAmount(multiply);
        itemEntity.setSkuQuantity(seckillOrder.getNum());

        orderItemService.save(itemEntity);
    }

    /**
     * 保存订单
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity entity = order.getOrder();
        entity.setModifyTime(new Date());
        this.save(entity);

        List<OrderItemEntity> items = order.getOrderItems();
        orderItemService.saveBatch(items);
    }

    private OrderCreateTo createOrder(){
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //1. 生成一个订单号
        String timeId = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrder(timeId);
        //2.获取到所有的订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(timeId);
        //3.验价
        computePrice(orderEntity,orderItemEntities);
        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(orderItemEntities);
        return orderCreateTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        Integer growth = 0;
        Integer integra = 0;
        for (OrderItemEntity entity : orderItemEntities) {
            BigDecimal realAmount = entity.getRealAmount();
            BigDecimal couponAmount = entity.getCouponAmount();
            BigDecimal integrationAmount = entity.getIntegrationAmount();
            BigDecimal promotionAmount = entity.getPromotionAmount();
            Integer giftGrowth = entity.getGiftGrowth();
            Integer giftIntegration = entity.getGiftIntegration();
            total = total.add(realAmount);
            promotion = promotion.add(promotionAmount);
            integration = integration.add(couponAmount);
            coupon = coupon.add(integrationAmount);
            growth += giftGrowth;
            integra += giftIntegration;
        }
        //1。订单价格相关
        orderEntity.setTotalAmount(total);
        // 应付总额， 加运费
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(integration);
        //设置积分等信息
        orderEntity.setGrowth(growth);
        orderEntity.setIntegration(integra);
        //删除状态 未删除
        orderEntity.setDeleteStatus(0);
    }

    private OrderEntity buildOrder(String timeId) {
        UserMemberVo userMemberVo = OrderInterceptor.loginUser.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(timeId);
        orderEntity.setModifyTime(new Date());
        orderEntity.setMemberId(userMemberVo.getId());
        //2.获取收货地址信息
        OrderSubmitVo submitVo = orderConfirmVoThreadLocal.get();
        R fare = wareFeignService.getFare(submitVo.getAddrId());
        FareVo fareVo = fare.getData("data", new TypeReference<FareVo>() {
        });
        // 设置运费信息
        orderEntity.setFreightAmount(fareVo.getFare());
        //设置收货人信息
        orderEntity.setReceiverCity(fareVo.getMemberReceiveAddressTo().getCity());
        orderEntity.setReceiverDetailAddress(fareVo.getMemberReceiveAddressTo().getDetailAddress());
        orderEntity.setReceiverName(fareVo.getMemberReceiveAddressTo().getName());
        orderEntity.setReceiverPhone(fareVo.getMemberReceiveAddressTo().getPhone());
        orderEntity.setReceiverProvince(fareVo.getMemberReceiveAddressTo().getProvince());
        orderEntity.setReceiverRegion(fareVo.getMemberReceiveAddressTo().getRegion());

        //设置订单的相关状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);

        return orderEntity;
    }

    /**
     * 构建所有订单项数据
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后缺点每个购物项的价格
        List<OrderItemVo> orderItemVos = cartFeignService.currentUserItems();
        if(orderItemVos!=null&&orderItemVos.size()>0){
            List<OrderItemEntity> collect = orderItemVos.stream().map(item -> {
                OrderItemEntity itemEntity = buildOrderItem(item);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 构建每一个订单项数据
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo item) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1. 订单信息， 订单号
        //2.商品的spu信息
        Long skuId = item.getSkuId();
        R spuInfoBySkuId = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoTo data = spuInfoBySkuId.getData("data", new TypeReference<SpuInfoTo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());
        //3.商品的sku信息
        itemEntity.setSkuId(item.getSkuId());
        itemEntity.setSkuName(item.getTitle());
        itemEntity.setSkuPic(item.getImage());
        itemEntity.setSkuPrice(item.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(item.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(item.getCount());

        //4。商品的优惠信息（不做）
        //5.商品的积分信息
        itemEntity.setGiftGrowth(item.getPrice().intValue());
        itemEntity.setGiftIntegration(item.getPrice().intValue());
        //6.设置单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前购物项的实际金额、  总额- 各种优惠
        BigDecimal origin = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal realAmount = origin.subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(realAmount);
        return itemEntity;
    }

}